<?php
// +----------------------------------------------------------------------
// | Description: 数据库备份类
// +----------------------------------------------------------------------
// | Author: orchief
// +----------------------------------------------------------------------
namespace App\HttpController\Admin;

use App\Common\Controller\Common;
use App\Utility\Extend\Baksql;
use EasySwoole\Config;

class DataBase extends Common
{
    protected $dataList; // 待处理分页处理
    protected $finalDataList = []; // 处理完的分页数据
    protected $page;
    protected $limit = 15; // 默认每页15条数据
    /**
     * 数据列表分页化
     */
    protected function PageList()
    {
        $this->page = isset($this->param['page']) ? $this->param['page'] : 1;
        $this->limit = isset($this->param['limit']) ? $this->param['limit'] : 15;

        $this->dataList;
        $start = $this->limit * ($this->page - 1);
        $this->finalDataList['dataCount'] = count($this->dataList);
        $this->finalDataList['list'] = array_slice($this->dataList, $start, $this->limit);
    }

    public function GETIndex()
    {
        $type = isset($this->param['tp']) ? $this->param['tp'] : 1;
        $name = isset($this->param['name']) ? $this->param['name'] : 1;
        $database = Config::getInstance()->getConf('database');
        $sql = new Baksql($database);
        switch ($type) {
            case "backup": //备份
                $info = exec('mysqldump -u'.$database['username'].' -p'.$database['password'].' '.$database['database'].' > /var/www/html/app/Databak/$(date +%Y%m%d_%H%M%S).sql');
                break;
            case "dowonload": //下载
                $data = $sql->downloadFile($name);
                $this->jsonData($data);
                break;
            case "restore": //还原
                $info = exec('mysql -u'.$database['username'].' -p'.$database['password'].' '.$database['database'].' < /var/www/html/app/Databak/'.$name);
                break;
            case "del": //删除
                $info = $sql->delfilename($name);
                break;
            default: //获取备份文件列表
                $this->dataList = $sql->get_filelist();
                $this->PageList();
                $info = $this->finalDataList;
                break;
        }
        $this->jsonData($info);
    }
}
